import subprocess
import re, socket, json
# import chardet

# def print_hi(name):
#     with pdfplumber.open("C:\software\pythonProject\HW2024-08-01微步威胁情报合集.pdf") as pdf:
#         first_page = pdf.pages[0]
#         print(first_page.chars[0])

def ping_domain():
    domain = "m.bala.iask.sina.com.cn"
    try:
        ip = socket.gethostbyname(domain)
        print(ip)
    except:
        print("有异常，不是正确的域名，忽略")

    # status, res = subprocess.getstatusoutput(f"ping {domain}")
    # print(f'状态：{status}')
    # print(f'执行结果：{res}')
    # ips = re.findall(ipv4_strict_pattern, res)
    #
    # #域名能解析ip处理
    # if ips:
    #     for ip in list(set(ips)):
    #         print(ip)

def parse_domain():
    # text = '【2408】2024 年度机场特殊贡献团队名单.docx.exe'
    # exclude_pattern = r'[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.exe$'
    # for domain in re.findall(exclude_pattern, text):
    #     print(domain)
    domain = "docx.exe"
    ipv4_strict_pattern = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
    not_domain_ip = ["192.168.10.1"]
    cmd = f"nslookup -type=A {domain}"

    try:
        process = subprocess.Popen(f"nslookup -type=A {domain}", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        output, unused_err = process.communicate(timeout=30)
        # output = output.decode("gbk")
        # unused_err = unused_err.decode("gbk")
        print(output)
        print(unused_err)
    except Exception as e:
        process.kill()
        print(e, e.__traceback__.tb_lineno, '行')

    ips = re.findall(ipv4_strict_pattern, output)

    #域名能解析ip处理
    if ips:
        for ip in list(set(ips)):
            if ip not in  not_domain_ip:
                print(ip)



# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # ping_domain()
    parse_domain()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
